package com.zzyl.nursing.service.impl;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.Period;
import java.time.format.DateTimeFormatter;
import java.util.List;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONArray;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zzyl.common.constant.ScheduleConstants;
import com.zzyl.common.utils.CodeGenerator;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.CheckInApplyDto;
import com.zzyl.nursing.dto.CheckInConfigDto;
import com.zzyl.nursing.dto.CheckInContractDto;
import com.zzyl.nursing.service.*;
import com.zzyl.nursing.vo.CheckInConfigVo;
import com.zzyl.nursing.vo.CheckInDetailVo;
import com.zzyl.nursing.vo.CheckInElderVo;
import com.zzyl.nursing.vo.ElderFamilyVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.CheckInMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.function.Consumer;
import java.util.function.Function;

/**
 * 入住Service业务层处理
 *
 * @author zzyl
 * @date 2025-10-16
 */
@Service
public class CheckInServiceImpl extends ServiceImpl<CheckInMapper, CheckIn> implements ICheckInService {
    private static final int STATUS_ENABLE = 1;
    private static final int STATUS_DISABLE = 0;

    @Autowired
    private CheckInMapper checkInMapper;

    @Autowired
    private IElderService elderService;

    @Autowired
    private IBedService bedService;

    @Autowired
    private ICheckInService checkInService;

    @Autowired
    private ICheckInConfigService checkInConfigService;

    @Autowired
    private IContractService contractService;

    /**
     * 查询入住
     *
     * @param id 入住主键
     * @return 入住
     */
    @Override
    public CheckIn selectCheckInById(Long id) {
        return getById(id);
    }

    /**
     * 查询入住列表
     *
     * @param checkIn 入住
     * @return 入住
     */
    @Override
    public List<CheckIn> selectCheckInList(CheckIn checkIn) {
        return checkInMapper.selectCheckInList(checkIn);
    }

    /**
     * 新增入住
     *
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int insertCheckIn(CheckIn checkIn) {
        return save(checkIn) ? 1 : 0;
    }

    /**
     * 修改入住
     *
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int updateCheckIn(CheckIn checkIn) {
        return updateById(checkIn) ? 1 : 0;
    }

    /**
     * 批量删除入住
     *
     * @param ids 需要删除的入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInByIds(Long[] ids) {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除入住信息
     *
     * @param id 入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInById(Long id) {
        return removeById(id) ? 1 : 0;
    }


    /**
     * 申请入住
     *
     * @param checkInApplyDto
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void apply(CheckInApplyDto checkInApplyDto) {
        // 判断老人是否已经入住
        Elder elder = BeanUtil.toBean(checkInApplyDto.getCheckInElderDto(), Elder.class);
        // 根据身份证号查询数据库
        Elder selectElderByIdCardNo = elderService.getOne(Wrappers.<Elder>lambdaQuery().eq(Elder::getIdCardNo, elder.getIdCardNo()));
        // 获取床位信息
        Bed bed = bedService.getById(checkInApplyDto.getCheckInConfigDto().getBedId());
        // 补充老人信息
        elder.setBedId(bed.getId());
        elder.setBedNumber(bed.getBedNumber());
        elder.setStatus(STATUS_ENABLE);
        // 查到了判断是否为空
        if (ObjectUtils.isNotEmpty(selectElderByIdCardNo)) {
            if (selectElderByIdCardNo.getStatus() == STATUS_ENABLE) {
                // 不为空，状态为已入住，禁止重复入住
                throw new RuntimeException("目前正在入住");
            } else {
                // 判断老人是退租的老用户,更改状态
                elderService.updateById(elder);
            }
        }
        // 老人是新用户,新增老人信息
        elderService.save(elder);
        // 家属信息不用数据库，JSON格式存在备注中
        // 新增入住信息
        CheckInConfigDto checkInConfigDto = checkInApplyDto.getCheckInConfigDto();
        CheckIn checkIn = BeanUtil.toBean(checkInConfigDto, CheckIn.class);
        checkIn.setElderId(elder.getId());
        checkIn.setElderName(elder.getName());
        checkIn.setIdCardNo(elder.getIdCardNo());
        checkIn.setBedNumber(bed.getBedNumber());
        checkIn.setStatus(STATUS_DISABLE);
        checkIn.setRemark(JSON.toJSONString(checkInApplyDto.getElderFamilyDtoList()));
        checkInService.save(checkIn);
        // 新增入住配置信息
        CheckInConfig checkInConfig = BeanUtil.toBean(checkInConfigDto, CheckInConfig.class);
        checkInConfig.setCheckInId(checkIn.getId());
        checkInConfigService.save(checkInConfig);
        // 新增合同信息
        CheckInContractDto checkInContractDto = checkInApplyDto.getCheckInContractDto();
        Contract contract = BeanUtil.toBean(checkInContractDto, Contract.class);
        contract.setElderId(Math.toIntExact(elder.getId()));
        contract.setContractNumber(CodeGenerator.generateContractNumber());
        contract.setElderName(elder.getName());
        contract.setStartDate(checkInConfigDto.getStartDate());
        contract.setEndDate(checkInConfigDto.getEndDate());
        contract.setStatus(checkInConfigDto.getStartDate().isBefore(LocalDateTime.now()) ? STATUS_ENABLE : STATUS_DISABLE);
        contractService.save(contract);
    }

    /**
     * 查询入住详情
     *
     * @param id 入住id
     * @return
     */
    @Override
    public CheckInDetailVo detail(Long id) {
        CheckInDetailVo checkInDetailVo = new CheckInDetailVo();
        // 查询入住信息
        CheckIn checkIn = checkInService.getById(id);
        CheckInConfigVo checkInConfigVo = BeanUtil.toBean(checkIn, CheckInConfigVo.class);
        // 查询老人
        Elder elder = elderService.getById(checkIn.getElderId());
        CheckInElderVo checkInElderVo = BeanUtil.toBean(elder, CheckInElderVo.class);

        // 设置年龄，使用DateTimeFormatter指定格式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        LocalDate birthday = LocalDate.parse(elder.getBirthday(), formatter);
        checkInElderVo.setAge(Period.between(birthday, LocalDate.now()).getYears());
        // 查询家属信息

        String elderFamilyVoListString = checkIn.getRemark();
        // 正确方式：直接解析为 List<ElderFamilyVo>
        List<ElderFamilyVo> elderFamilyVoList = JSON.parseArray(elderFamilyVoListString, ElderFamilyVo.class);
        // 查询配置
        CheckInConfig checkInConfig = checkInConfigService.getOne(Wrappers.<CheckInConfig>lambdaQuery().eq(CheckInConfig::getCheckInId, checkIn.getId()));
        BeanUtils.copyProperties(checkInConfig, checkInConfigVo);
        // 查询签约办理
        Contract selectContract = contractService.getOne(Wrappers.<Contract>lambdaQuery().eq(Contract::getElderId, elder.getId()));
        Contract contract = BeanUtil.toBean(selectContract, Contract.class);
        // 封装所有数据
        CheckInDetailVo inDetailVo = CheckInDetailVo.builder()
                .checkInElderVo(checkInElderVo)
                .elderFamilyVoList(elderFamilyVoList)
                .checkInConfigVo(checkInConfigVo)
                .contract(contract)
                .build();

        return inDetailVo;
    }
}
